package senpec.qc.harmony.base.mybatisplus;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import senpec.qc.harmony.base.exception.NoResultException;
import senpec.qc.harmony.system.user.UserMapper;

import java.util.List;

@Slf4j
public class IBaseServiceImpl<M extends IBaseMapper<T>, T extends IBaseEntity<T>> extends ServiceImpl<IBaseMapper<T>, T> implements IBaseService<T> {

    @Autowired
    private M iBaseMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<T> getById(Long id) {
        T selectById = iBaseMapper.selectById(id);
        if (selectById == null) {
            throw new NoResultException("未找到该数据");
        }
        return Result.ok(iBaseMapper.selectById(id));
    }

    @Override
    public Result<T> getOneByCondition(String columnName, Object columnValue) {
        T t = iBaseMapper.selectOne(new QueryWrapper<T>().eq(StringUtils.camelToUnderline(columnName), columnValue));
        if (t != null) {
            setCreatorAndUpdater(t);
        }
        return Result.ok(t);
    }

    @Override
    public Result<List<T>> getListByCondition(String columnName, Object columnValue) {
        return Result.ok(iBaseMapper.selectList(new QueryWrapper<T>().eq(StringUtils.camelToUnderline(columnName), columnValue)));
    }

    @Override
    public Result<List<T>> getListByConditions(T conditions) {
        return Result.ok(iBaseMapper.selectList(null));
    }

    @Override
    public Result<T> insertOne(T entity) {
        System.out.println(entity);
        return iBaseMapper.insert(entity) > 0 ? Result.ok(entity) : Result.error(entity);
    }

    @Override
    public Result<?> physicalDeleteById(Long id) {
        return iBaseMapper.physicalDeleteById(id) > 0 ? Result.ok().msg("删除成功") : Result.error().msg("删除失败");
    }

    @Override
    public Result<?> logicalDeleteById(Long id) {
        return iBaseMapper.deleteById(id) > 0 ? Result.ok().msg("逻辑删除成功") : Result.error().msg("逻辑删除失败");
    }

    @Override
    public Result<T> updateOne(T entity) {
        setVersion(entity);
        return this.updateById(entity) ? Result.ok(entity).msg("更新成功") : Result.error(entity).msg("更新失败");
    }

    @Override
    public Result<?> activeById(Long id) {
        return iBaseMapper.activeById(id) > 0 ? Result.ok().msg("激活成功") : Result.error().msg("激活");
    }

    public void setCreatorAndUpdater(T entity) {
        entity.setCreator(userMapper.selectById(entity.getCreatorId()));
        entity.setUpdater(userMapper.selectById(entity.getUpdaterId()));
    }
}